.PHONY:clean all

export PREFIX := /opt/cross_compiler/i386-elf-gcc
export TARGET := i386-elf
export PATH := ${PREFIX}/bin:${PATH}

NASM = nasm

CC=/usr/bin/g++
CFLAGS = -g -O0 -m16 -fno-pie -Wall -ffreestanding -c -nostdlib

LD = ld
LDFLAGS = -melf_i386
# LD = /usr/bin/gcc
# LD = i386-elf-gcc
# LDFLAGS = -static-libgcc -m16

GDB = /usr/bin/gdb

QEMU = qemu-system-i386

INCLUDE_DIR=

# debug文件夹里的makefile文件需要最后执行，所以这里需要执行的子目录要排除debug文件夹，
# 这里使用awk排除了debug文件夹，读取剩下的文件夹
SUBDIRS=$(shell ls -l | grep ^d | \
			awk '{if($$9 != "debug") \
					if($$9 != "cpu") \
					if($$9 != "kernel") \
					if($$9 != "drivers") \
					print $$9}')

#记住当前工程的根目录路径
ROOT_DIR=$(shell pwd)
#最终bin文件的名字，可以更改为自己需要的
BIN=os-image.bin
#目标文件所在的目录
OBJS_DIR=$(ROOT_DIR)/debug/obj
#bin文件所在的目录
BIN_DIR=$(ROOT_DIR)/debug/bin



#将以下变量导出到子shell中，本次相当于导出到子目录下的makefile中
export NASM CC CFLAGS LD LDFLAGS GDB QEMU BIN OBJS_DIR BIN_DIR ROOT_DIR
#注意这里的顺序，需要先执行SUBDIRS最后才能是DEBUG
all: build

run: build
	# ${QEMU} -vga std -fda ${BIN_DIR}/os-image.bin
	# ${QEMU} -blockdev driver=file,node-name=f0,filename=${BIN_DIR}/os-image.bin -device floppy,drive=f0 \
				#  -device floppy, filename=${BIN_DIR}/boot.bin
	# ${QEMU} -vga std -fda ${BIN_DIR}/os-image.bin -fda ${BIN_DIR}/boot.bin
	${QEMU} -vga std -drive file=${BIN_DIR}/os-image.bin,id=drive0 \
						-drive file=${BIN_DIR}/boot.bin,id=drive1\
						-boot order=a
	

debug: build
	# ${QEMU} -vga std -fda ${BIN_DIR}/os-image.bin -gdb tcp::1234 -S &
	${QEMU} -vga std -drive file=${BIN_DIR}/os-image.bin,id=drive0 \
						-drive file=${BIN_DIR}/boot.bin,id=drive1\
						-boot order=a \
						-gdb tcp::1234 -S &
	pkill gdbgui
	gdbgui -g '$(GDB) -ex "target remote localhost:1234"' &
	# ${GDB} -ex "target remote localhost:1234" -ex "symbol-file kernel.elf"


build: MKDIR $(SUBDIRS) LINK

MKDIR:
	@mkdir -p $(BIN_DIR)
	@mkdir -p $(OBJS_DIR)

#递归执行子目录下的makefile文件，这是递归执行的关键
$(SUBDIRS): ECHO
	make -C $@

LINK:ECHO
	make -C debug

ECHO:
	@echo $(SUBDIRS)


clean:
	rm -rf $(OBJS_DIR)/*
	rm -rf $(BIN_DIR)/*
